<!DOCTYPE html>
<title>Test behaviour of autoplay muted videos with regards to visibility</title>
<script src="../resources/testharness.js"></script>
<script src="../resources/testharnessreport.js"></script>
<body>
<script>
  internals.settings.setAutoplayPolicy('user-gesture-required');
  internals.runtimeFlags.autoplayMutedVideosEnabled = true;

  var gCycleCount = 0;

  var video;

  function runStepsWhenInvisible(t) {
    assert_true(video.paused);
    video.style.top = '0px';

    video.onplay = null;
    video.onpause = t.unreached_func();
    video.addEventListener('play', t.step_func(_ => runStepsWhenVisible(t)), { once: true });
  }

  function runStepsWhenVisible(t) {
    assert_false(video.paused);

    if (gCycleCount++ >= 3) {
      t.done();
      return;
    }
    video.style.top = '-10000px';

    video.onpause = null;
    video.onplay = t.unreached_func();
    video.addEventListener('pause', t.step_func(_ => runStepsWhenInvisible(t)), { once: true });
  }

  async_test(function(t) {
    // Create a video off screen.
    {
      video = document.createElement('video');
      video.src = 'content/test.ogv';
      video.muted = true;
      video.autoplay = true;
      video.loop = true;
      video.style.position = 'absolute';
      video.style.top = '-10000px';
      document.body.appendChild(video);
    }

    video.addEventListener('canplay', t.step_func(_ => runStepsWhenInvisible(t)), { once : true });
  });
</script>
